package com.atguigu.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author ：pkq
 * @date ：Created in 2022/1/5 13:21
 * @description：
 * @modified By：
 * @version: $
 */
@Component
public class MyLB implements LoadBalancer{


    private AtomicInteger atomicInteger = new AtomicInteger(0);

    private int getAndIncrement(){
        int current;
        int next;
        do {
            current = atomicInteger.get();
            next = current > Integer.MAX_VALUE ? 0 : current + 1;
        }while (!atomicInteger.compareAndSet(current,next));
        System.out.println(next);
        return next;
    }

    @Override
    public ServiceInstance getInstances(List<ServiceInstance> instances) {

        int i = this.getAndIncrement() % instances.size();
        return instances.get(i);
    }
}
